/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */
"use strict";
let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
// let logger = require('morgan');
let log4js = require('log4js');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let session = require('express-session');
let FileStore = require('session-file-store')(session);
let fs = require('fs');

log4js.configure(require('./utils/log4js'));
global.log4js = log4js;
global.config = require('./utils/config.js');
global.tool = require('./utils/tool');
global.weChatUtil = require('./utils/wechat');

let i18n = require('i18n');

let app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.set('case sensitive routing', true);
app.set('strict routing', true);
app.set('trust proxy', true);

global.config.i18n.directory = path.join(__dirname, global.config.i18n.directory);
i18n.configure(global.config.i18n);
app.use(i18n.init);
global.tool.traversalFolderSync(path.join(__dirname, 'utils\\local'), {
    eachFile : function (_path, pathArr, level) {
        let data = fs.readFileSync(_path, 'utf8');
        fs.writeFileSync(path.join(__dirname, 'public\\locales',
            pathArr[level].replace('.json', '.js')),
            "Dolphin.i18n.addMessages(" + data + ');');
    }
});

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// app.use(logger('dev'));
app.use(log4js.connectLogger(log4js.getLogger("http"), {
    level: 'debug',
    format: ':method | :status | :response-time ms | :url '
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
    secret: 'keyboard cat',
    resave: true,
    name: 'yams.site.sid',
    saveUninitialized: true,
    cookie: {maxAge: 1800000},
    store: new FileStore({
        path: 'sessions/site'
    })
}));

app.use('/', require('./routes/index'));
app.use('/view', require('./routes/view'));
app.use('/api', require('./routes/data'));
app.use('/collect', require('./routes/collect'));
app.use('/dataport.aspx', require('./routes/collect'));
app.use('/mp', require('./routes/mp'));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    let err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers
app.use(function (err, req, res, next) {
    if (err.status == 404 || err.message.indexOf('Failed to lookup view') > -1) {
        res.render('notFound', {
            message: err.message,
            error: err
        });
    } else if (err.status == 401) {
        res.render(req.session.endType + '/forbid', {
            message: err.message,
            error: err
        });
    } else {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    }
});

app.get("/*",function (req,res,next) {
    req.session.userData = {
        userId: 1,
        userCode: 'admin',
        userName: 'Admin',
        language: 'zh',
        customerId: null,
        vendorId: null,
        logoUrl : '/uploadFiles/images/logo.png',
        accountType: 1,
        company: [],
        topCustomer:body.null
    };
    next();
})

module.exports = app;
